__author__ = 'zoulida'
import QUANTAXIS as QA
import pandas as pd
from pandas import DataFrame as DF
from sdufe.tools.santai3.tools.wrapperZLD import time_me
from functools import lru_cache

class allZhangtings:

    def __init__(self):
        self.frame = DF()
        self.startday = '2019-06-01'
        self.endday = '2020-07-01'

    #frame = DF()
    def getAlldays(self):
        pass
    def getOneday(self):
        pass

    @time_me
    def filterStocksFromDataFrame(self):
        import sdufe.tools.santai3.tools.dataframeToCSV as dataframeToCSV
        df = dataframeToCSV.openCsv("/volume/zhangting.csv")
        print(df)
        pass

    def filterStocks(self):
        df = self.openShelve()
        if df is None:
            df = self.getAllStocks()
        pass

    @time_me
    def getAllStocks(self):
        stocklistframe = QA.QA_fetch_stock_list_adv()
        lenth = stocklistframe.__len__()
        i = 0
        for index, row in stocklistframe.iterrows():
            print('正在计算涨停日线，code = ', index, '已经完成》》》》》》》》》》》》》》》》》', i/lenth)
            namestr = row['name']
            self.getOneStocks(code=index, name = namestr)
            i = i + 1
            if i > 10000:#这里用于测试，一共4000个股票，设置的小一点可以快速迭代
                break
        print(self.frame)
        self.frame.to_csv(path_or_buf='/volume/zhangting.csv', sep=str(','), na_rep='', float_format=None, columns=None,
                          header=True,
                          index=True,
                          index_label=None, mode='w', encoding='GBK', compression=None, quoting=None, quotechar='"',
                          line_terminator='\n', chunksize=None, tupleize_cols=None, date_format=None, doublequote=True,
                          escapechar=None, decimal='.')

        #self.saveShelve(self.frame)#不再存储了
        return self.frame

    def openShelve(self):
        import shelve
        filename = 'StocksShelve'
        from sdufe.Config import FILEPATH
        dirstr = FILEPATH.SHELVEDIR.value

        pathname = dirstr + filename
        try:
            shelveDict = shelve.open(pathname)
        except Exception as e:
            print('出错，没有文件%s。现在立即新建，并重复执行' % pathname)
            import os
            os.makedirs(pathname)
            shelveDict = shelve.open(pathname)

        name = self.startday + '-' + self.endday
        if name in shelveDict:
            df = shelveDict[name]
            #print(listResult)
            shelveDict.close()
            return df
        else:
            return  None


    def saveShelve(self, dframe):
        import shelve
        filename = 'StocksShelve'
        from sdufe.Config import  FILEPATH
        dirstr = FILEPATH.SHELVEDIR.value

        pathname = dirstr + filename
        try:
            shelveDict = shelve.open(pathname)
        except Exception as e:
            print('出错，没有文件%s。现在立即新建，并重复执行' % pathname)
            import os
            os.makedirs(pathname)
            shelveDict = shelve.open(pathname)

        name = self.startday + '-' + self.endday
        shelveDict[name] = dframe
        shelveDict.close()


    def appendSeries(self, prerow, row, name):
        #prerow.rename({'date':'pre-date'}, inplace = True)
        prerow.rename(lambda x: 'pre-' + x, inplace=True)
        #print(prerow)
        row['name'] = name
        newRow = row.append(prerow)
        newRow['change'] = (newRow['open']/newRow['pre-high'] - 1) * 100#开盘就卖出盈利比
        newRow['chuquan'] = self.chuquan(newRow) #是否是因为除权涨停
        newRow['opendays'] = self.IPONewLabel(newRow)
        #print(newRow)
        self.frame = self.frame.append(newRow, ignore_index=True)


    @lru_cache(maxsize=64)
    def getChuquanimformation(self, code):
        data = QA.QAFetch.QATdx.QA_fetch_get_stock_xdxr(code)
        return data

    def IPONewLabel(self, row):
        data = self.getChuquanimformation(row['code'])
        firstrow = data.iloc[0]
        ipoDate = firstrow['date']

        # 字符串转成时间戳str->timestamp
        #oneDay_str = "2019-2-6 12:1:0"
        import time
        import datetime

        ipoDate_timestamp = datetime.datetime.strptime(ipoDate, "%Y-%m-%d")
        opendays = (row['pre-date'] - ipoDate_timestamp).days
        return opendays
        #print("字符串转成日期datetime", ipoDate_timestamp)
        #print((row['pre-date'] - ipoDate_timestamp).days)


        pass

    def chuquan(self, row):
        import time
        data = self.getChuquanimformation(row['code'])
        #daystr = time.strftime("%Y-%m-%d %H:%M:%S", row['pre-date'])
        chuquan = None
        if row['pre-date'] in data.index:#pre-date与date有一个除权都要标识
            chuquan = data.loc[row['pre-date']]
        if row['date'] in data.index:
            chuquan = data.loc[row['date']]
        if chuquan is None:
            return 0
        else:
            import pandas as pd
            if isinstance(chuquan, pd.DataFrame):
                #print('DataFrame')
                #print(chuquan['category'][0])
                return chuquan['category'][0]
            else:
                return chuquan['category']
        '''1': '除权除息', '2': '送配股上市', '3': '非流通股上市', '4': '未知股本变动',
            '5': '股本变化',
            '6': '增发新股', '7': '股份回购', '8': '增发新股上市', '9': '转配股上市',
            '10': '可转债上市',
            '11': '扩缩股', '12': '非流通股缩股', '13': '送认购权证', '14': '送认沽权证'''

    def getOneStocks(self, code = '002740',  name = None):

        dataobj = QA.QA_fetch_stock_day_adv(code, self.startday, self.endday)
        if dataobj is None:
            return
        data2 = dataobj.data
        data2['high_limit'] = dataobj.high_limit
        data3 = data2.reset_index()
        #print(data3)
        '''for index, row in data3.iterrows():
            #print(row)
            #frame = frame.append( row)
            if row.close == row.high_limit:
                print(row)'''

        for i in range(0, len(data3)):
            #frame = frame.append(data3.iloc[i])
            row = data3.iloc[i]
            if row.high == row.high_limit and i+1 != len(data3):#过滤股票
                if row.low == row.high_limit:#一字涨停
                    continue
                #print(row)
                #print(data3.iloc[i+1])
                self.appendSeries(row, data3.iloc[i+1], name)

        #for row in data2.itertuples(index=True, name='Pandas'):
        #    print(row)
        #    frame.append(row)


'''        datelist = dataobj.date
        for i in datelist:#2020-01-02 00:00:00
            #print(i)
            print(data2.loc[i])
        print(data2.query("date == '2020-01-02'"))#多重索引,取值
        print(data2.index[0][0])
        #if data2.close'''


if __name__ == '__main__':
    AZ = allZhangtings()
    #AZ.getAllStocks()
    #AZ.getOneStocks('603986')
    AZ.filterStocksFromDataFrame()
